﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using KZ400B.AxleSettings;

namespace KZ400B.Controls
{
    /// <summary>
    /// AxleRunState.xaml 的交互逻辑
    /// </summary>
    public partial class AxleRunStateForMulti : UserControl
    {
        public AxleRunStateForMulti()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(AxleRunStateForMulti_Loaded);
            Unloaded += new RoutedEventHandler(AxleRunStateForMulti_Unloaded);
            
        }

        


        private bool m_IsChecked;

        public bool IsChecked
        {
            get { return m_IsChecked; }
            set { m_IsChecked = value;
            cmbTarget.IsEnabled = m_IsChecked;
            btnStop.IsEnabled = m_IsChecked;
            }
        }


        public bool SendSetting(ref double step)
        {
            int direct = Axle.Direction.ForwardDirection.Value;
            double totalStep = 0;

            if (double.TryParse(cmbTarget.SelectedItem.ToString(), out totalStep))
            {
                totalStep = AxleCacheManager.AxleList[AxleName].ComputeAddtion(totalStep, ref direct);
                step = totalStep;
                if (totalStep == 0.0F)
                {
                    return true;
                }

                AxleCacheManager.AxleList[AxleName].Addtion = totalStep;


                Axle.Direction dirt = new Axle.Direction(direct);
                double m_runSpeed = AxleCacheManager.AxleList[AxleName].RunSpeed;
                double pwm = AxleCacheManager.AxleList[AxleName].getRunPwm(m_runSpeed);

                //AxleManager.Run(AxleName
                //    , dirt, pwm
                //    , AxleCacheManager.AxleList[AxleName].TotalStep);

                bool setRst = AxleManager.ParameterSetting(AxleName
                    , dirt
                    , pwm
                    , AxleCacheManager.AxleList[AxleName].TotalStep);
                if (setRst)
                {
                    AxleCacheManager.Update(AxleCacheManager.AxleList[AxleName]);
                    //AxleManager.Run(AxleName);
                }
                //else
                //{

                //}
                return setRst;
            }
            return false;
        }

        public double TargetPostion
        {
            get {
                int targetPostion = 0;
                if (int.TryParse(cmbTarget.SelectedItem.ToString(), out targetPostion))
                {
                    return targetPostion;
                }
                return 0;
            }
        }

        //private Axle m_Axle;
        private static Dictionary<int,RunningUnit> s_runningUnits = new Dictionary<int,RunningUnit>()
        {
               {(int)RunningUnits.Step, new RunningUnit((int)RunningUnits.Step,"步数")}
               ,{(int)RunningUnits.Millimeter,new RunningUnit((int)RunningUnits.Millimeter,"毫米")}
               ,{(int)RunningUnits.Radian,new RunningUnit((int)RunningUnits.Radian,"度数")}
        };
        string m_axleName = string.Empty;
        void AxleRunStateForMulti_Loaded(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(AxleName))
            {
                throw new Exception("AxleName 不能为空");
            }
            //m_Axle = AxleCacheManager.getAxle(AxleName);
            m_axleName = AxleName;
            grpAxle.Header = string.Format("{0}轴", AxleName);
            try
            {
                if (AxleCacheManager.AxleList[AxleName] == null)
                    return;
                //targetBind(AxleCacheManager.AxleList[AxleName].RunTarget);
                targetBind(MySetting.getUnionStoreAxleValue(m_axleName));
                IsChecked = MySetting.getUnionCheckStoreAxleValue(m_axleName);//false;
                chkAxle.IsChecked = IsChecked;
                labAxlePostion.Content = AxleCacheManager.AxleList[AxleName].DisplayPosition.ToString(MySetting.PositionDisDeciFormatter);
                labUnit.Content = s_runningUnits[(int)AxleCacheManager.AxleList[AxleName].RunningUnit].Name;
                //AxleManager.OnAxlePostionChange += new AxlePositionChange(AxleManager_OnAxlePostionChange);
            }
            catch (Exception ex)
            {
                Data.AxleStateBarMsg.Instance.AxleState = string.Format("组件加载异常:[{0}]",ex.Message);
            }
        }

        void setPosition(string axleName, double position)
        {
            labAxlePostion.Dispatcher.Invoke(new Action(delegate()
                {
                    if (axleName.Equals(AxleName))
                    {
                        PositionCacheManager.ChangePosition(AxleName, position, true);
                    }
                }));
        }

        void AxleManager_OnAxlePostionChange(string axleName, Axle axle, double position)
        {
            setPosition( axleName,position);
        }

        void AxleRunStateForMulti_Unloaded(object sender, RoutedEventArgs e)
        {
        }

        public static DependencyProperty AxleNameProperty = DependencyProperty.Register(
        "AxleName", typeof(string)
        , typeof(AxleRunStateForMulti)
        , new PropertyMetadata(string.Empty)
        );

        public string AxleName
        {
            get { return (string)GetValue(AxleNameProperty); }
            set { SetValue(AxleNameProperty, value); }
        }

        public static DependencyProperty AxlePositionProperty = DependencyProperty.Register(
    "AxlePosition", typeof(double)
    , typeof(AxleRunStateForMulti)
     , new PropertyMetadata(Axle.DefaultPosition, new PropertyChangedCallback(OnPositionChange))
    );

        public double AxlePosition
        {
            get { return (double)GetValue(AxlePositionProperty); }
            set { SetValue(AxlePositionProperty, value); }
        }

        private static void OnPositionChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
             AxleRunStateForMulti control = (AxleRunStateForMulti)d;
             if (AxleCacheManager.AxleList[control.AxleName] == null) return;
             double pos = control.AxlePosition;
             control.labAxlePostion.Content = pos.ToString(MySetting.PositionDisDeciFormatter);
            //不需要更新数据库,因为在主界面也注册了位置更改程序
        }


        
    //    /// <summary>
    //    /// 目标位置
    //    /// </summary>
    //    public static DependencyProperty AxleTargetProperty = DependencyProperty.Register(
    //"AxleTarget", typeof(double)
    //, typeof(AxleRunStateForMulti)
    // , new PropertyMetadata(Axle.DefaultPosition, new PropertyChangedCallback(OnTargetChange))
    //);

    //    public double AxleTarget
    //    {
    //        get { return (double)GetValue(AxleTargetProperty); }
    //        set { SetValue(AxleTargetProperty, value); }
    //    }

    //    private static void OnTargetChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
    //    {
    //        AxleRunStateForMulti control = (AxleRunStateForMulti)d;
    //        //if (AxleCacheManager.AxleList[control.AxleName] == null) return;
    //        //double pos = control.AxlePosition;
    //        //control.labAxlePostion.Content = pos.ToString(MySetting.PositionDisDeciFormatter);
    //        //不需要更新数据库,因为在主界面也注册了位置更改程序
    //        MySetting.setUnionStoreAxleValue(control.m_axleName, control.AxleTarget);
    //        control.targetBind(control.AxleTarget);
    //    }



        public static DependencyProperty AxlePositionUnitProperty = DependencyProperty.Register(
        "AxlePositionUnit", typeof(string)
        , typeof(AxleRunStateForMulti)
         , new PropertyMetadata((string)string.Empty, new PropertyChangedCallback(OnAxlePositionUnitChange))
        );

        public string AxlePositionUnit
        {
            get { return (string)GetValue(AxlePositionUnitProperty); }
            set { SetValue(AxlePositionUnitProperty, value); }
        }

        private static void OnAxlePositionUnitChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            AxleRunStateForMulti control = (AxleRunStateForMulti)d;
            control.labUnit.Content = control.AxlePositionUnit;
        }


        void targetBind(double tValue)
        {
            List<int> mList = new List<int> { 1, 2, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 100, 150 };//();
            //for (int i = 1; i < 101; i++)
            //{
            //    mList.Add(i);
            //}

            cmbTarget.ItemsSource = mList;
            if (tValue != 0)
            {
                cmbTarget.BindValue(tValue);
            }
            else { cmbTarget.SelectedIndex = 0; }
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            AxleManager.Stop(AxleName);
        }

        private void chkAxle_Checked(object sender, RoutedEventArgs e)
        {
            IsChecked = true;
            MySetting.setUnionCheckStoreAxleValue(m_axleName,true);//false;

        }

        private void chkAxle_Unchecked(object sender, RoutedEventArgs e)
        {
            IsChecked = false;
            MySetting.setUnionCheckStoreAxleValue(m_axleName, false);//false;
        }

        private void cmbTarget_DataChanged(object sender)
        {
            double dValue = 0;
            if (cmbTarget.SelectedItem != null && double.TryParse(cmbTarget.SelectedItem.ToString(), out dValue))
            {
                if (!AxleCacheManager.AxleList[AxleName].RunTarget.ToString(MySetting.PositionDisDeciFormatter)
                    .Equals(dValue.ToString(MySetting.PositionDisDeciFormatter)))
                {
                    AxleCacheManager.AxleList[AxleName].RunTarget = dValue;
                    AxleCacheManager.Update(AxleCacheManager.AxleList[AxleName]);
                    //changeParam();
                }
                MySetting.setUnionStoreAxleValue(m_axleName, dValue);
            }
        }




    }
}
